import { Provide } from '@midwayjs/core';
import { House } from '../entity/house.entity';
import {
  HouseAddDto,
  HouseEditDto,
  HouseIdRequired,
  HouseStatusDto,
  Pagination,
} from '../model';
import { User } from '../entity/user.entity';

// 定义扁平化 DTO
class HouseUseDTO {
  userName: string;
  userPhone: number;
  constructor(house: any) {
    if (house.user) {
      this.userName = house.user.name;
      this.userPhone = house.user.phone;
    }
    delete house.user;
    Object.assign(this, house);
  }
}

@Provide()
export class HouseService {
  async getList(req: Pagination) {
    const { count, rows } = await House.findAndCountAll({
      limit: req.pageSize,
      offset: (req.pageNo - 1) * req.pageSize,
      include: [
        {
          model: User,
          attributes: ['name', 'phone'],
        },
      ],
      attributes: { exclude: ['userId', 'createdAt', 'updatedAt'] },
      order:[['id','DESC']]
    });
    const list = rows.map(house => new HouseUseDTO(house.get({ plain: true })));
    return {
      count,
      rows: list,
    };
  }

  async listByPerson(req: Pagination, userId: number) {
    const { count, rows } = await House.findAndCountAll({
      where: {
        userId: userId,
      },
      limit: req.pageSize,
      offset: (req.pageNo - 1) * req.pageSize,
      include: [
        {
          model: User,
          attributes: ['name', 'phone'],
        },
      ],
      attributes: { exclude: ['userId', 'createdAt', 'updatedAt'] },
      order:[['id','DESC']]
    });
    const list = rows.map(house => new HouseUseDTO(house.get({ plain: true })));
    return {
      count,
      rows: list,
    };
  }

  async addItem(req: HouseAddDto, userId: number) {
    const result = await House.create({
      ...req,
      userId: userId,
    });
    return result;
  }

  async editItem(req: HouseEditDto & HouseStatusDto) {
    const result = await House.update(
      {
        ...req,
      },
      {
        where: {
          id: req.id,
        },
      }
    );
    return result;
  }

  async delItem(req: HouseIdRequired) {
    const result = await House.destroy({
      where: {
        id: req.id,
      },
    });
    return result;
  }
  async byIdItem(req: HouseIdRequired) {
    const result = await House.findOne({
      where: {
        id: req.id,
      },
      include: [
        {
          model: User,
          attributes: ['name', 'phone'],
        },
      ],
      attributes: { exclude: ['userId', 'createdAt', 'updatedAt'] },
    });
    const newResult = new HouseUseDTO(result.get({ plain: true }))
    return newResult;
  }
  async auditItem(req: HouseIdRequired & HouseStatusDto) {
    const result = await House.update(
      {
        status: req.status,
      },
      {
        where: {
          id: req.id,
        },
      }
    );
    return result;
  }
}
